package com.chonor.mall.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.chonor.mall.common.CommonPage;
import com.chonor.mall.common.CommonResult;
import com.chonor.mall.dto.AdminLoginParam;
import com.chonor.mall.dto.AdminParam;
import com.chonor.mall.dto.UpdateAdminPasswordParam;
import com.chonor.mall.dto.UploadRoleParam;
import com.chonor.mall.enums.GenderEnum;
import com.chonor.mall.enums.UserStatusEnum;
import com.chonor.mall.model.Admin;
import com.chonor.mall.model.Role;
import com.chonor.mall.service.AdminService;
import com.chonor.mall.service.RoleService;
import com.chonor.mall.util.EnumUtil;
import com.chonor.mall.vo.AdminDetailVO;
import com.chonor.mall.vo.AdminVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 后台员工管理Controller
 */
@Controller
@Api(tags = "AdminController", description = "后台员工管理")
@RequestMapping("/admin")
public class AdminController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Admin> register(@Validated @RequestBody AdminParam adminParam) {
        Admin admin = adminService.register(adminParam);
        if (admin == null) {
            return CommonResult.failed("用户已存在");
        }
        return CommonResult.success(admin);
    }

    @ApiOperation(value = "登录以后返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@Validated @RequestBody AdminLoginParam adminLoginParam) {
        String token = adminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword());
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = adminService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAdminInfo(Principal principal) {
        if(principal==null){
            return CommonResult.unauthorized(null);
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUsername(username);
        Map<String, Object> data = new HashMap<>();
        data.put("username", admin.getUsername());
        data.put("menus", roleService.getMenuList(admin.getId()));
        data.put("avatar", admin.getAvatar());
        List<Role> roleList = adminService.getRoleList(admin.getId());
        if(CollUtil.isNotEmpty(roleList)){
            List<String> roles = roleList.stream().map(Role::getName).collect(Collectors.toList());
            data.put("roles",roles);
        }
        return CommonResult.success(data);
    }

    @ApiOperation(value = "分页获取员工列表")
    @RequestMapping(value = "/adminList", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAdminList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        //获取总数
        Long adminNum = adminService.count();

        List<Admin> adminList = adminService.list(pageNum, pageSize);

        AdminVO adminVO = new AdminVO();
        adminVO.setAdminNum(adminNum);
        convertAdmin(adminList, adminVO);

        return CommonResult.success(adminVO);
    }

    private void convertAdmin(List<Admin> adminList, AdminVO adminVO){
        if(Objects.isNull(adminList) || adminList.size() <= 0) return;
        List<AdminVO.Admin> admins = new ArrayList<>(adminList.size());
        for (Admin a : adminList) {
            AdminVO.Admin admin = new AdminVO.Admin();
            BeanUtils.copyProperties(a, admin);
            admin.setGender(EnumUtil.getMessage(GenderEnum.class, a.getGender()));
            admin.setStatus(EnumUtil.getMessage(UserStatusEnum.class, a.getStatus()));
            admin.setBirthday(DateUtil.formatDate(a.getBirthday()));
            admin.setCreateAt(DateUtil.formatDate(a.getCreateat()));
            admins.add(admin);
        }
        adminVO.setAdmins(admins);
    }


    @ApiOperation(value = "登出功能")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult logout() {
        return CommonResult.success(null);
    }

    @ApiOperation("根据用户名或姓名分页获取用户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<Admin>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<Admin> adminList = adminService.list(keyword, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(adminList));
    }

    @ApiOperation("获取指定用户信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Admin> getItem(@PathVariable Long id) {
        Admin admin = adminService.getItem(id);
        return CommonResult.success(admin);
    }

    @ApiOperation("获取指定用户信息")
    @RequestMapping(value = "/getItem/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<AdminDetailVO> getDetail(@PathVariable Long id) {
        AdminDetailVO detail = adminService.getDetail(id);
        if(Objects.isNull(detail)){
            return CommonResult.failed("用户id不能为空");
        }
        return CommonResult.success(detail);
    }

    @ApiOperation("修改指定用户信息")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@PathVariable Long id, @RequestBody Admin admin) {
        int count = adminService.update(id, admin);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("修改指定用户密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePassword(@Validated @RequestBody UpdateAdminPasswordParam updatePasswordParam) {
        int status = adminService.updatePassword(updatePasswordParam);
        if (status > 0) {
            return CommonResult.success(status);
        } else if (status == -1) {
            return CommonResult.failed("提交参数不合法");
        } else if (status == -2) {
            return CommonResult.failed("找不到该用户");
        } else if (status == -3) {
            return CommonResult.failed("旧密码错误");
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("删除指定用户信息")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@PathVariable Long id) {
        int count = adminService.delete(id);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("修改帐号状态")
    @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) {
        Admin admin = new Admin();
        admin.setStatus(status);
        int count = adminService.update(id,admin);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("给用户分配角色")
    @RequestMapping(value = "/role/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateRole(@RequestBody UploadRoleParam uploadRoleParam) {
        if(Objects.isNull(uploadRoleParam.getAdminId()) || Objects.isNull(uploadRoleParam.getRoleIds())) return CommonResult.failed("请求参数有误");
        if(uploadRoleParam.getRoleIds().size() < 1) return CommonResult.failed("请选择要分配的角色");
        int count = adminService.updateRole(uploadRoleParam.getAdminId(), uploadRoleParam.getRoleIds());
        if (count >= 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("获取指定用户的角色")
    @RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<Role>> getRoleList(@PathVariable Long adminId) {
        List<Role> roleList = adminService.getRoleList(adminId);
        return CommonResult.success(roleList);
    }

}
